﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using EnvDTE;
using Microsoft.VisualStudio.TemplateWizard;
using System.IO;
using System.Linq;
using System.Reflection;
using System.IO.Compression;
using ICSharpCode.SharpZipLib.Zip;

namespace NeosSDI.MVC4.ProjectTemplateWizard
{
    public class IWizardImplementationChild : IWizard
    {
        private SolutionWizard solutionWizard;

        // This method is called before opening any item that 
        // has the OpenInEditor attribute.
        public void BeforeOpeningFile(ProjectItem projectItem)
        {
        }

        public void ProjectFinishedGenerating(Project project)
        {
            if (project != null && project.Name.Contains("Transverse") && !IWizardImplementation.PackageCreated)
            {
                FileInfo fi = new FileInfo(project.FullName);
                DirectoryInfo di = fi.Directory.Parent.Parent.Parent;
                DirectoryInfo packagesDirectory = di.CreateSubdirectory("packages");
                Assembly assembly = Assembly.LoadWithPartialName("NeosSDI.MVC4.ProjectTemplateWizard");

                string mes = "";
                foreach (var str in assembly.GetManifestResourceNames())
                {
                    if (str.Contains("packages"))
                    {
                        WriteResourceToFile(assembly, str, packagesDirectory.FullName + "\\packages.zip");
                        UnZipFile(packagesDirectory.FullName + "\\packages.zip");
                        File.Delete(packagesDirectory.FullName + "\\packages.zip");
                    }
                }
                IWizardImplementation.PackageCreated = true;
            }
        }


        public static void WriteResourceToFile(Assembly targetAssembly, string resourceName, string filepath)
        {
            using (Stream s = targetAssembly.GetManifestResourceStream(resourceName))
            {
                if (s == null)
                {
                    throw new Exception("Cannot find embedded resource '" + resourceName + "'");
                }
                byte[] buffer = new byte[s.Length];
                s.Read(buffer, 0, buffer.Length);
                using (BinaryWriter sw = new BinaryWriter(File.Open(filepath, FileMode.Create)))
                {
                    sw.Write(buffer);
                }
            }
        }

        public static bool UnZipFile(string InputPathOfZipFile)
        {
            bool ret = true;
            try
            {
                if (File.Exists(InputPathOfZipFile))
                {
                    string baseDirectory = Path.GetDirectoryName(InputPathOfZipFile);

                    using (ZipInputStream ZipStream = new ZipInputStream(File.OpenRead(InputPathOfZipFile)))
                    {
                        ZipEntry theEntry;
                        while ((theEntry = ZipStream.GetNextEntry()) != null)
                        {
                            if (theEntry.IsFile)
                            {
                                if (theEntry.Name != "")
                                {
                                    string strNewFile = @"" + baseDirectory + @"\" +

theEntry.Name;
                                    if (File.Exists(strNewFile))
                                    {
                                        continue;
                                    }

                                    using (FileStream streamWriter = File.Create(strNewFile))
                                    {
                                        int size = 2048;
                                        byte[] data = new byte[2048];
                                        while (true)
                                        {
                                            size = ZipStream.Read(data, 0, data.Length);
                                            if (size > 0)
                                                streamWriter.Write(data, 0, size);
                                            else
                                                break;
                                        }
                                        streamWriter.Close();
                                    }
                                }
                            }
                            else if (theEntry.IsDirectory)
                            {
                                string strNewDirectory = @"" + baseDirectory + @"\" +

theEntry.Name;
                                if (!Directory.Exists(strNewDirectory))
                                {
                                    Directory.CreateDirectory(strNewDirectory);
                                }
                            }
                        }
                        ZipStream.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                ret = false;
            }
            return ret;
        }


        public static void CopyStream(Stream input, Stream output)
        {
            // Insert null checking here for production
            byte[] buffer = new byte[8192];

            int bytesRead;
            while ((bytesRead = input.Read(buffer, 0, buffer.Length)) > 0)
            {
                output.Write(buffer, 0, bytesRead);
            }
        }

        // This method is only called for item templates,
        // not for project templates.
        public void ProjectItemFinishedGenerating(ProjectItem
            projectItem)
        {
        }

        // This method is called after the project is created.
        public void RunFinished()
        {
        }

        public void RunStarted(object automationObject,
            Dictionary<string, string> replacementsDictionary,
            WizardRunKind runKind, object[] customParams)
        {
            try
            {
                // Add custom parameters.
                replacementsDictionary.Add("$solutionNameChild$",
                    IWizardImplementation.globalDictionary["$solutionName$"].ToString());

    
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString()+","+ ex.StackTrace);
            }
        }

        //public static Dictionary<string, string> globalDictionary;

        // This method is only called for item templates,
        // not for project templates.
        public bool ShouldAddProjectItem(string filePath)
        {
            return true;
        }
    }
}